package com.thread.threadfirst.studyThread3;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentSkipListMap;
import java.util.concurrent.CountDownLatch;

/**
 * 3、测试哪个并发容器效率更高
 * SkipListMap是基于跳表结构，插入效率高且是排好序的
 * <p>
 * HashTable是最老的，线程安全的，所有的实现都是带锁的(synchronized)，但是效率低，很少用了。
 * 而HashMap可以用Collections.synchronizedXXX。即加锁的HashMap
 */
public class T1 {

    public static void main(String[] args) {
//        Map<String,String> map=new ConcurrentHashMap();  //需要300多秒
        Map<String, String> map = new ConcurrentSkipListMap<>();  //高并发且有序，但插入效率低，因为是有序的

//        Map<String,String> map=new Hashtable<>();  //需要400多秒
//        Map<String,String> map=new HashMap<>();  //Collections.synchronizedXXX
//        TreeMap 非并发下的有序，同样插入效率低
        Thread[] threads = new Thread[100];
        CountDownLatch latch = new CountDownLatch(threads.length);
        Random r = new Random();
        long start = System.currentTimeMillis();

        for (int i = 0; i < threads.length; i++) {
            threads[i] = new Thread(() -> {
                for (int j = 0; j < 10000; j++) map.put("a" + r.nextInt(100000), "a" + r.nextInt(100000));
                latch.countDown();
            });
        }
        Arrays.asList(threads).forEach(o -> o.start());
        try {
            latch.await();  //阻止主线程继续往下执行
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        long end = System.currentTimeMillis();
        System.out.println(end - start);
    }

}
